{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-02-21T02:19:33.654974Z",
     "start_time": "2020-02-21T02:19:33.626476Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 1 B B {(0, 0)} 1\n",
      "0 2 C C {(0, 1), (0, 0)} 2\n",
      "0 3 C E {(0, 1), (0, 0), (0, 2)} 3\n",
      "0 1 C B {(0, 1), (0, 0), (0, 2)} 3\n",
      "1 2 C C {(0, 1), (0, 0), (0, 2)} 3\n",
      "1 3 E S {(0, 1), (0, 0), (0, 2), (1, 2)} 4\n",
      "1 1 E F {(0, 1), (0, 0), (0, 2), (1, 2)} 4\n",
      "2 2 E E {(0, 1), (0, 0), (0, 2), (1, 2)} 4\n",
      "2 3 D E {(0, 1), (1, 2), (0, 0), (2, 2), (0, 2)} 5\n",
      "2 1 D D {(0, 1), (1, 2), (0, 0), (2, 2), (0, 2)} 5\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def exist(board, word):\n",
    "    n,m = len(board),len(board[0])\n",
    "    def dfs(i,j,k,visited):\n",
    "        if k == len(word):return True\n",
    "        for dx,dy in [(0,1),(0,-1),(1,0),(-1,0)]:\n",
    "            nx,ny = i+dx,j+dy\n",
    "            if 0<=nx<n and 0<=ny<m and (nx,ny) not in visited and board[nx][ny] == word[k]:\n",
    "                visited.add((nx,ny))\n",
    "                if dfs(nx, ny, k+1, visited):\n",
    "                    return True\n",
    "                visited.remove((nx,ny))\n",
    "                \n",
    "        return False\n",
    "    for i in range(n):\n",
    "        for j in range(m):\n",
    "            if board[i][j] == word[0] and dfs(i,j,1,{(i,j)}):\n",
    "                return True\n",
    "    return False\n",
    "board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]]\n",
    "word = \"ABCCED\"\n",
    "exist(board, word)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
